﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BoYuanCore.Framework.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Routing;
using Serilog;

namespace BoYuanCore.WebUI.Code.Filter
{

    //Startup,Configure 添加 app.UseExceptionHandler(UrlAddress.ErrorUrl);//全局异常拦截 
    [Obsolete("此方法弃用。/error 页面获取异常(非跳转url方式显示异常)")]
    public class ExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            //https://blog.csdn.net/qq_43144405/article/details/105553936
            if (!context.ExceptionHandled)//如果异常没处理
            {
                //判断请求是否来源ajax
                //if (context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest")
                string num = Guid.NewGuid().ToString("N");
                string msg = num+" >> "+context.Exception.Message.LineBreak()+ context.Exception.StackTrace;
                Log.Error(msg);
                var errorPage =UrlAddress.ErrorUrl + "?num="+ num; // new UrlHelper(context).Action("Index", "Error");
                context.Result = new RedirectResult(errorPage);
            }
            context.ExceptionHandled = true;//设置异常已被处理
        }

        /// <summary>
        /// 异步发生异常时进入
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            OnException(context);
            return Task.CompletedTask;
        }
    }
}
